using UnityEngine;

/// <summary>
/// 【推荐】动态适配16:9画面比例，自动添加黑边处理
/// 适用平台：
/// - WebGL / 移动端 / 不支持SetResolution的平台
/// - 希望固定比例展示内容，避免拉伸
/// 挂载方式：
/// - 将此脚本挂载到主摄像机（Camera）上
/// </summary>
[RequireComponent(typeof(Camera))]
public class FixedAspectRatioUpgrade : MonoBehaviour
{
    [Header("目标宽高比")]
    [Tooltip("默认16:9，即 1.7777...")]
    [SerializeField] private float targetAspect = 16f / 9f;

    private void Start()
    {
        ApplyAspectRatio();
    }

    private void ApplyAspectRatio()
    {
        Camera cam = GetComponent<Camera>();

        float screenAspect = (float)Screen.width / Screen.height;
        float scale = screenAspect / targetAspect;

        if (scale < 1.0f)
        {
            // 屏幕更高，添加上下黑边
            float inset = (1.0f - scale) / 2.0f;
            cam.rect = new Rect(0f, inset, 1f, scale);
        }
        else
        {
            // 屏幕更宽，添加左右黑边
            float scaleWidth = 1.0f / scale;
            float inset = (1.0f - scaleWidth) / 2.0f;
            cam.rect = new Rect(inset, 0f, scaleWidth, 1f);
        }
    }
}
